/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.oauth.services;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.user.PartyAccount;
import com.koorz.modules.user.User;
import com.koorz.oauth.model.OAuthConstants;
import com.koorz.oauth.model.OAuthRequest;
import com.koorz.oauth.model.Response;
import com.koorz.oauth.model.Token;
import com.koorz.oauth.model.UserWrapper;
import com.koorz.oauth.model.Verb;
import com.koorz.oauth.model.tencent.TencentToken;
import com.koorz.utils.FileUtil;
import com.koorz.utils.IdManage;
import com.koorz.utils.LoginUtil.WeiboType;
import com.koorz.utils.SystemConfig;


/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-4-8 下午6:46:12
 * 版  本  号：1.0
 */
public class TencentService extends ApiService{
	
	private String curr_user_id = "https://graph.qq.com/oauth2.0/me";
	private String user_info_url = "https://graph.qq.com/user/get_user_info";
	private String send_weibo_url = "https://graph.qq.com/t/add_t";
	private String get_followers_url = "https://graph.qq.com/relation/get_fanslist";
	
	public String getOpenId(String accessToken){
		OAuthRequest request = createRequest(Verb.GET, curr_user_id);
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		Response response = request.send();
		if(response.isSuccessful()){
			JSONObject json = JSON.parseObject(StringUtils.substringBetween(response.getBody(), "(", ")"));
		    return json.getString("openid");
	    }
		return null;
	}
	
	public UserWrapper getUserInfo(String uid,String accessToken){
		OAuthRequest request = createRequest(Verb.GET, user_info_url);
		request.addQuerystringParameter("format", "json");
		request.addQuerystringParameter("oauth_consumer_key", SystemConfig.getValue("tercent_client_ID"));
		request.addQuerystringParameter("openid",uid);
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject json = JSON.parseObject(response.getBody());
	    	return wapperUser(json);
	    }
	    return null;
	}
	
	/**
	 * 
	 * 功能描述：qq好友列表还没有审核通过
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 下午2:32:33
	 * 参       数：
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public Page<UserWrapper> getUserFollowers(String accessToken,
			String uid,int page, int count) {
		OAuthRequest request = createRequest(Verb.GET, get_followers_url);
		request.addQuerystringParameter("openid", uid);
		request.addQuerystringParameter("oauth_consumer_key", SystemConfig.getValue("tercent_client_ID"));
		request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		request.addQuerystringParameter("format", "json");
		request.addQuerystringParameter("reqnum", count+"");
		request.addQuerystringParameter("startindex", (page-1)*count+"");
		request.addQuerystringParameter("mode", "1");
		
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject json = JSON.parseObject(response.getBody());
	    	if(json.getIntValue("ret") == 0){
	    		JSONObject data = json.getJSONObject("data");
	    		if(data.getIntValue("hasnext") == 0){
	    			JSONArray info = data.getJSONArray("info");
	    			List<UserWrapper> users = new ArrayList<UserWrapper>();
	    			for(int i=0;i<info.size();i++){
	    				JSONObject userObj = info.getJSONObject(i);
	    				UserWrapper user = new UserWrapper();
	    				if(StringUtils.isEmpty(userObj.getString("head"))){
	    					user.setAvatar(GlobalConstant.DEFAULT_AVATAR);
	    				}else {
	    					user.setAvatar(userObj.getString("head")+"/30");
	    				}
	    				if(StringUtils.isEmpty(userObj.getString("head"))){
	    					user.setAvatarLarge(GlobalConstant.DEFAULT_AVATAR_LARGE);
	    				}else {
	    					user.setAvatarLarge(userObj.getString("head")+"/50");
	    				}
	    		    	
	    		    	user.setLoc(userObj.getString("location"));
	    		    	user.setNickname(userObj.getString("nick"));
	    		    	user.setUid(userObj.getString("name"));
	    				users.add(user);
	    			}
	    			return new Page<UserWrapper>(users,page,count,page,count);
	    		}
	    	}
	    }
	    return new Page<UserWrapper>(new ArrayList<UserWrapper>(0),page,count,0,0);
	}

	/**
	 * 
	 * 功能描述：
	 * 作        者：尹东东
	 * 创建时间：2013-4-9 下午3:46:11
	 * 参       数：uidqq用户id，status分享的内容，url资源链接（用户在本站的个人主页），atUser要@的用户（调用QQ空间分享不能at用户，微博接口可以,但同步不到QQ空间）
	 * 返       回:无
	 * 异       常：无
	 * 版  本 号：1.0
	 */
	public int inviteFriend(String accessToken,String uid,String clientip,String status,String atUser) {
		String inviteFriendTemplate = "我正在用米蕊网听音乐%s。%s @%s ";
		OAuthRequest request = createRequest(Verb.POST, send_weibo_url);
		request.addBodyParameter("oauth_consumer_key", SystemConfig.getValue("tercent_client_ID"));
		request.addBodyParameter("openid",uid);
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		request.addBodyParameter("clientip",clientip);
		request.addBodyParameter("format","json");
		request.addBodyParameter("content", String.format(inviteFriendTemplate,GlobalConstant.DOMAIN_HOST,status,atUser));
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}

	public int shareStatus(String accessToken,String openid,String clientip,String status) {
		//String shareTemplate = "分享  %s 的歌曲 ♫%s:%s %s （分享自 @米蕊网）";
		OAuthRequest request = createRequest(Verb.POST, send_weibo_url);
		request.addBodyParameter("oauth_consumer_key", SystemConfig.getValue("tercent_client_ID"));
		request.addBodyParameter("openid",openid);
		request.addBodyParameter(OAuthConstants.ACCESS_TOKEN,accessToken);
		request.addBodyParameter("clientip",clientip);
		request.addBodyParameter("format","json");
		//String url = GlobalConstant.DOMAIN_HOST+"/"+uid;
		request.addBodyParameter("content",status);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	@Override
	protected UserWrapper wapperUser(JSONObject obj) {
		if(obj.getIntValue("ret") == 0){
			UserWrapper user = new UserWrapper();
	    	user.setAvatar(obj.getString("figureurl_1"));
	    	user.setAvatarLarge(obj.getString("figureurl_2"));
	    	user.setDesc("");
	    	//m--男，f--女,n--未知
	    	if("男".equals(obj.getString("gender"))){
	    		user.setGender(1);
	    	}else if("女".equals(obj.getString("gender"))){
	    		user.setGender(0);
	    	}else {
	    		user.setGender(-1);
	    	}
	    	user.setLoc("");
	    	user.setNickname(obj.getString("nickname"));
	    	user.setUid("");
			return user;
		}
		return null;
	}

	@Override
	protected List<UserWrapper> wapperUsers(JSONArray array) {
		List<UserWrapper> users = new ArrayList<UserWrapper>();
		for(int i=0;i<array.size();i++){
			JSONObject userObj = array.getJSONObject(i);
			users.add(wapperUser(userObj));
		}
		return users;
	}
	
	public static void main(String[] args) {
		/**
		 * 200
openId:196A2D24EE47430A68D529786A9D2E64
accessToken:E12FE56E2C190C474FB86B9E8BAAB47D
200
		 */
		String token = "F9CB7FE8DFC3EC6BA720916A417103A0";
		String openId = "196A2D24EE47430A68D529786A9D2E64";
		String clientip = "61.172.10.172";
		TencentService ts = new TencentService();
		//ts.getUserInfo(openId, token);
		//ts.getUserFollowers(token, openId, 1, 10);
		//String accessToken,String uid,String clientip,String status,String atUser
		//ts.inviteFriend(token,openId,"61.172.10.172","是不是一样的","noah0202");
		//ts.testShare();
		//String accessToken,String openid,String clientip,String status,String uid,String username,String songName
		ts.shareStatus(token, openId, clientip, "不错哦");
	}

	@Override
	public User bindUser(Token objClass) {
		TencentToken accessToken = (TencentToken) objClass;
		String openId = getOpenId(accessToken.getAccessToken());
		UserWrapper userWrapper = getUserInfo(openId, accessToken.getAccessToken());
		User user = User.dao.findFirst("select u.id from user as u inner join party_account as pa on pa.user_id=u.id where pa.account_id=?",openId);	
		if (user == null) {
			user = new User();
			String userId = IdManage.nextId(IdManage.USER);
			user.set("id", userId);
			user.set("nickname",userWrapper.getNickname());
			user.set("gender",userWrapper.getGender());
			user.set("signature","");
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.set("created_time", new Timestamp(Calendar.getInstance().getTimeInMillis()));
			user.set("score", 0);
			user.set("used_disk", 0);
			user.set("ranking", 0);
			user.set("upload_imitative_num", 0);
			user.set("upload_original_num", 0);
			user.set("upload_other_num", 0);
			user.set("artist_rate", 0.0);
			user.set("agents_rate", 0.0);
			user.set("singer_name", userWrapper.getNickname());
			user.set("region", "");
			user.set("description", "");
			user.set("user_website",GlobalConstant.DOMAIN_HOST + "/" + userId);
			user.set("tel", "");
			user.set("email", "");
			user.set("grade_id", "000000");
			//user.set("user_type",UserType.SELF.ordinal());
			user.save();
			
			PartyAccount account = new PartyAccount();
			account.set("id", IdManage.nextId(IdManage.PARTYACCOUNT));
			account.set("user_id", userId);
			account.set("account_id", openId);
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", "");
			account.set("expires_in", accessToken.getExpiresIn());
			account.set("type", WeiboType.TERCENT.ordinal());
			account.save();
//			for(int i=0;i<GlobalConstant.DEFAULTIMGS.length;i++){
//				ArtistsCover cover = new ArtistsCover();
//				cover.set("id", IdManage.nextId(IdManage.COVER));
//				cover.set("user_id", user.getStr("id"));
//				cover.set("img_url", GlobalConstant.DEFAULTIMGS[i]);
//				cover.set("is_show", 1);
//				cover.set("time", DateUtil.getNowDateTime());
//				cover.set("type", 0);
//				cover.save();
//			}
			
//			Db.update("insert into user_weibo_setting values(?,?,?,?,?,?)", 
//					IdManage.nextId(IdManage.USER_WEIBO_SETTING),
//					userId,WeiboType.TERCENT.ordinal(),1,1,1);
			user.put("grade_name", "流浪歌手");
			user.put("grade_level", "Lv1");
			user.put("platform",WeiboType.TERCENT.ordinal());
		} else {
			user.set("nickname",userWrapper.getNickname());
			user.set("gender",userWrapper.getGender());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.update();
			
			PartyAccount account = PartyAccount.dao.findFirst("select id,user_id,access_token,expires_in from party_account where user_id=? and account_id=?", 
					new Object[]{user.getStr("id"),openId});
			account.set("access_token", accessToken.getAccessToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.update();
			
			user = User.dao.findFirst("select u.id,u.avatar,u.avatar_large,u.nickname,u.midou,u.user_website,u.score,u.ranking,g.name as grade_name,g.level as grade_level from user as u " +
						" inner join grade as g on g.id=u.grade_id " +
						" where u.id=?",user.getStr("id"));
			user.put("platform",WeiboType.TERCENT.ordinal());
		}
		return user;
	}
}
